Add Binary

Given two binary strings, return their sum (also a binary string).

For example,

a = "11"

b = "1"

Return "100".

Solution:

  1. public class Solution {
  2. public String addBinary(String s1, String s2) {
  3. int i = s1.length() - 1, j = s2.length() - 1, c = 0;
  4. String s = "";
  5. while (i >= 0 || j >= 0 || c == 1) {
  6. int a = (i < 0) ? 0 : s1.charAt(i--) - '0';
  7. int b = (j < 0) ? 0 : s2.charAt(j--) - '0';
  8. s = (char)('0' + a ^ b ^ c) + s;
  9. c = (a + b + c) >> 1;
  10. }
  11. return s;
  12. }
  13. }